package com.estar.assistsurvy.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.estar.assistsurvy.R;
import com.estar.assistsurvy.constant.Constants;
import com.estar.assistsurvy.entity.RequestBaseInfo;
import com.estar.assistsurvy.entity.ResponseMsg;
import com.estar.assistsurvy.thread.BaseInfoThread;
import com.estar.assistsurvy.utils.Base64;
import com.estar.assistsurvy.utils.FileUtils;
import com.estar.assistsurvy.utils.GlideCircleTransform;
import com.estar.assistsurvy.utils.GlideUtiles;
import com.estar.assistsurvy.utils.MightypleUtil;
import com.estar.assistsurvy.utils.ValidatorUtils;
import com.estar.assistsurvy.widget.OptionPopwindow;
import com.estar.assistsurvy.widget.SelectPicPopupWindow;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BaseInfoActivity extends BaseActivity implements OnClickListener{

	private LinearLayout select_industry;
	private TextView returnBack,industry_name,effect_time;
	private EditText ceti_name,credit_num;
	private Button submit;
	private ImageView front_photo,back_photo,driving_img,travlling_img,head_img;
	private InputMethodManager imm;
	private Calendar calendar;
	private long currentTime;
	private SelectPicPopupWindow ppw;
	private final static int GRAPH=0,ALBUM=1;
	private String picPath;
	private int from=0;
	private Intent intent;
	private Bitmap image;
	private OptionPopwindow optionPop;
	private String type,uuid,deviceId,name,phone,address,iDCard,
	iDCardPhotoJust="",iDCardPhotoback="",headPortrait="",driverLicenseImg="",travelLicenseImg="";
	private SharedPreferences preference;
	private RequestManager glideRequest;
	private String[] options=new String[]{"公估人员","同业","社会人员"};
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;

			case 0:
				ResponseMsg message=new ResponseMsg();
				message=(ResponseMsg) msg.obj;
				showShortToast(message.getMessages());
				intent=new Intent(BaseInfoActivity.this, CetificationActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
				break;

			default:
				break;
			}
		};
	};

	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_baseinfo);
		initView();
	}

	private void initView(){
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
		ceti_name=find(R.id.ceti_name);
		credit_num=find(R.id.credit_num);
		effect_time=find(R.id.effect_time);
		effect_time.setOnClickListener(this);
		front_photo=find(R.id.front_photo);
		front_photo.setOnClickListener(this);
		back_photo=find(R.id.back_photo);
		back_photo.setOnClickListener(this);
		driving_img=find(R.id.driving_img);
		driving_img.setOnClickListener(this);
		travlling_img=find(R.id.travlling_img);
		travlling_img.setOnClickListener(this);
		head_img=find(R.id.head_img);
		head_img.setOnClickListener(this);
		select_industry=find(R.id.select_industry);
		select_industry.setOnClickListener(this);
		industry_name=find(R.id.industry_name);
		submit=find(R.id.submit);
		submit.setOnClickListener(this);
		imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		calendar=Calendar.getInstance();
		preference=getSharedPreferences("user", MODE_PRIVATE);
		uuid=preference.getString("uuid", "");
		phone=preference.getString("phoneNumber", "");
		deviceId=MightypleUtil.getDeviceId(BaseInfoActivity.this);
		address="中国";
		head_img.requestFocus();
		glideRequest = Glide.with(this);
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.returnBack:
			intent=new Intent(BaseInfoActivity.this, CetificationActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
			break;

		case R.id.effect_time:
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘  
			new DatePickerDialog(BaseInfoActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {

				@Override
				public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
					// TODO Auto-generated method stub
					// 更新EditText控件日期 小于10加0
					effect_time.setText(new StringBuilder()
							.append(year)
							.append("-")
							.append((month + 1) < 10 ? "0"
									+ (month + 1) : (month + 1))
							.append("-")
							.append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
				}
			}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();

			break;

		case R.id.front_photo:
			from=0;
			selectPhoto();
			break;

		case R.id.back_photo:
			from=1;
			selectPhoto();
			break;

		case R.id.driving_img:
			from=2;
			selectPhoto();
			break;

		case R.id.travlling_img:
			from=3;
			selectPhoto();
			break;

		case R.id.head_img:
			from=4;
			selectPhoto();
			break;

		case R.id.select_industry:
			optionPop=new OptionPopwindow(BaseInfoActivity.this, new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// TODO Auto-generated method stub
					industry_name.setText(options[position]);
					type=String.valueOf(position+1);
					optionPop.dismiss();
				}
			}, options);
			// 设置optionPop显示的位置
			optionPop.showAtLocation(BaseInfoActivity.this
					.findViewById(R.id.industry_name), Gravity.CENTER
					| Gravity.CENTER_HORIZONTAL, 0, -150);
			break;

		case R.id.submit:
			name=ceti_name.getText().toString().trim();
			iDCard=credit_num.getText().toString().trim();
			if(deviceId==null||deviceId.equals("")){
				showShortToast("获取设备信息失败!");
			}else if(uuid==null||uuid.equals("")){
				showShortToast("获取用户信息失败!");
			}else if(type==null||type.equals("")){
				showShortToast("请选择认证角色!");
			}else if(name==null||name.equals("")){
				showShortToast("请填写真实姓名!");
			}else if(phone==null||phone.equals("")){
				showShortToast("获取注册手机失败!");
			}else if(iDCard==null||iDCard.equals("")||ValidatorUtils.isIDCard(iDCard)==Boolean.FALSE){
				showShortToast("请填写真实有效的身份证号码!");
			}else if(iDCardPhotoback==null||iDCardPhotoback.equals("")){
				showShortToast("请选择身份证反面照片!");
			}else if(iDCardPhotoJust==null||iDCardPhotoJust.equals("")){
				showShortToast("请选择身份证正面照片!");
			}else if(headPortrait.equals("")||headPortrait==null){
				showShortToast("请选择头像!");
			}else if(driverLicenseImg.equals("")||driverLicenseImg==null){
				showShortToast("请选择驾驶证照片!");
			}else if(travelLicenseImg.equals("")||travelLicenseImg==null){
				showShortToast("请选择行驶证照片!");
			}else{
				dialog=ProgressDialog.show(this, null, "正在提交信息", false, false);
				RequestBaseInfo baseInfo=new RequestBaseInfo(deviceId, uuid, type, name, phone, address, iDCard, iDCardPhotoJust, iDCardPhotoback, headPortrait, driverLicenseImg, travelLicenseImg);
				new BaseInfoThread(BaseInfoActivity.this, handler, baseInfo).start();

			}

			break;

		default:
			break;
		}
	}

	private void selectPhoto(){
		ppw=new SelectPicPopupWindow(BaseInfoActivity.this, new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//从相册获取相片
				intent=new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");  
				startActivityForResult(intent, ALBUM); 
				ppw.dismiss();
			}
		}, new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//调用系统相机获取照片
				intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				currentTime = System.currentTimeMillis();
				picPath=Environment
						.getExternalStorageDirectory()
						+ "/DCIM/"+"ESTAR"+currentTime + ".jpg";
				// 加载路径
				Uri uri = Uri.fromFile(new File(picPath));
				// 指定存储路径，这样就可以保存原图了
				intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				// 拍照返回图片
				startActivityForResult(intent, GRAPH);
				ppw.dismiss();
			}
		});
		// 设置ppw显示的位置
		ppw.showAtLocation(BaseInfoActivity.this
				.findViewById(R.id.front_photo), Gravity.CENTER
				| Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
//		super.onActivityResult(requestCode, resultCode, data);
		//		if(resultCode!=RESULT_OK){
		//			showShortToast("获取照片出错，请重试");
		//			return;
		//		}
		//		if(data==null){
		//			showShortToast("获取照片出错，请重试");
		//			return;
		//		}
		if(resultCode==RESULT_OK){
			if (requestCode==ALBUM) {

				ContentResolver resolver = getContentResolver();  
				//照片的原始资源地址  
				Uri originalUri = data.getData();
				//使用ContentProvider通过URI获取原始图片  
				try {
					image = MediaStore.Images.Media.getBitmap(resolver, originalUri);
					if(image!=null){
						
						ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
						image.compress(Bitmap.CompressFormat.JPEG, 60, baos);
						FileOutputStream fileOutputStream = null;
						File file=FileUtils.getPhotoFile();
						// 打开文件输出流
						fileOutputStream = new FileOutputStream(file);
						// 生成图片文件
						image.compress(Bitmap.CompressFormat.JPEG, 60, fileOutputStream);
						// 相片的完整路径
						picPath=file.getPath();
						switch (from) {
						case 0:
							GlideUtiles.loadIntoUseFitWidth(this, picPath, front_photo);
							iDCardPhotoJust=Base64.encode(baos.toByteArray());
							destoryBimap();
							break;

						case 1:
							GlideUtiles.loadIntoUseFitWidth(this, picPath, back_photo);
							iDCardPhotoback=Base64.encode(baos.toByteArray());
							destoryBimap();
							break;

						case 2:
							GlideUtiles.loadIntoUseFitWidth(this, picPath, driving_img);
							driverLicenseImg=Base64.encode(baos.toByteArray());
							destoryBimap();
							break;

						case 3:
							GlideUtiles.loadIntoUseFitWidth(this, picPath, travlling_img);
							travelLicenseImg=Base64.encode(baos.toByteArray());
							destoryBimap();
							break;

						case 4:
//							GlideUtiles.loadIntoUseFitWidth(this, picPath, head_img);
							glideRequest.load(picPath)
							.placeholder(R.drawable.icon_head)
							.transform(new GlideCircleTransform(BaseInfoActivity.this))
							.into(head_img);
							headPortrait=Base64.encode(baos.toByteArray());
							destoryBimap();
							break;

						default:
							break;
						}

						if(fileOutputStream!=null){
							fileOutputStream.close();
						}
						if(baos!=null){
							baos.close();
						}
					}else{
						showShortToast("相册照片获取失败");
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(requestCode==GRAPH){
				switch (from) {
				case 0:
					GlideUtiles.loadIntoUseFitWidth(this, picPath, front_photo);
					iDCardPhotoJust=Base64.encode(FileUtils.getBytes(picPath));
					break;

				case 1:
					GlideUtiles.loadIntoUseFitWidth(this, picPath, back_photo);
					iDCardPhotoback=Base64.encode(FileUtils.getBytes(picPath));
					break;

				case 2:
					GlideUtiles.loadIntoUseFitWidth(this, picPath, driving_img);
					driverLicenseImg=Base64.encode(FileUtils.getBytes(picPath));
					break;

				case 3:
					GlideUtiles.loadIntoUseFitWidth(this, picPath, travlling_img);
					travelLicenseImg=Base64.encode(FileUtils.getBytes(picPath));
					break;

				case 4:
//					GlideUtiles.loadIntoUseFitWidth(this, picPath, head_img);
					glideRequest.load(picPath)
					.placeholder(R.drawable.icon_head)
					.transform(new GlideCircleTransform(BaseInfoActivity.this))
					.into(head_img);
					headPortrait=Base64.encode(FileUtils.getBytes(picPath));
					break;

				default:
					break;
				}
			}
		}else{
			showShortToast("获取照片出错，请重试");
		}
	}

	/**
	 * 销毁图片文件
	 */
	private void destoryBimap()
	{
		if (image != null && ! image.isRecycled()) {
			image.recycle();
			image = null;
		}
	}

	//	private void selectPhoto(){
	//		ppw = new SelectPicPopupWindow(BaseInfoActivity.this,
	//				new OnClickListener() {
	//
	//					@Override
	//					public void onClick(View v) {
	//						// 从相册获取图片
	//						intent = new Intent();  
	//		                intent.setType("image/*");  
	//		                intent.setAction(Intent.ACTION_GET_CONTENT);  
	//				        startActivityForResult(intent, ALBUM);
	//						ppw.dismiss();
	//					}
	//				}, new OnClickListener() {
	//
	//					@Override
	//					public void onClick(View v) {// 从拍照获取图片
	//						// 进入手机的相机功能
	////						currentTime = System.currentTimeMillis();
	//						String state = Environment.getExternalStorageState();
	//						if (state.equals(Environment.MEDIA_MOUNTED)) {
	//						 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
	//			             intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); 
	//
	////						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
	////								.fromFile(new File(Environment
	////										.getExternalStorageDirectory()
	////										+ "/DCIM/", currentTime + ".jpg")));
	//						startActivityForResult(intent,
	//								GRAPH);
	//						}else {
	//				            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
	//				        }
	//						ppw.dismiss();
	//					}
	//				});
	//		// 设置ppw显示的位置
	//		ppw.showAtLocation(BaseInfoActivity.this
	//				.findViewById(R.id.front_photo), Gravity.CENTER
	//				| Gravity.CENTER_HORIZONTAL, 0, 0);
	//	}

	//	@Override
	//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	//		if (data != null) {  
	//            //取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意  
	//            Uri mImageCaptureUri = data.getData();  
	//            
	//            //返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取  
	//            if (mImageCaptureUri != null) {  
	//                try {  
	//                    //这个方法是根据Uri获取Bitmap图片的静态方法  
	//                    image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);  
	//                    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
	//                    if (image != null) {  
	//                    	switch (from) {
	//						case 0:
	//							front_photo.setImageBitmap(image); 
	//							
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							iDCardPhotoJust =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 1:
	//							back_photo.setImageBitmap(image); 
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							iDCardPhotoback =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 2:
	//							driving_img.setImageBitmap(image);
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							driverLicenseImg =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 3:
	//							travlling_img.setImageBitmap(image);
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							travelLicenseImg =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 4:
	//							Bitmap bm=BitmapUtils.toRoundBitmap(image);
	//							head_img.setImageBitmap(bm);
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							headPortrait =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						default:
	//							break;
	//						}
	//                         
	//                    }  
	//                } catch (Exception e) {  
	//                    e.printStackTrace();  
	//                }  
	//            } else {  
	//                Bundle extras = data.getExtras();  
	//                if (extras != null) {  
	//                    //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片  
	//                    image = extras.getParcelable("data");  
	//                    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
	//                    if (image != null) {  
	//                    	switch (from) {
	//						case 0:
	//							front_photo.setImageBitmap(image); 
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							iDCardPhotoJust =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 1:
	//							back_photo.setImageBitmap(image); 
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							iDCardPhotoback =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 2:
	//							driving_img.setImageBitmap(image);
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							driverLicenseImg =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 3:
	//							travlling_img.setImageBitmap(image);
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							travelLicenseImg =Base64.encode(baos.toByteArray());
	//							break;
	//							
	//						case 4:
	//							Bitmap bm=BitmapUtils.toRoundBitmap(image);
	//							head_img.setImageBitmap(bm);
	//							image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
	//							headPortrait =Base64.encode(baos.toByteArray());
	//							break;
	//
	//						default:
	//							break;
	//						}
	//                    }  
	//                }  
	//            }  
	//
	//        }
	//		
	//	}
	//	


	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//		super.onBackPressed();
		intent=new Intent(BaseInfoActivity.this, CetificationActivity.class);
		startActivity(intent);
		finish();
		overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);

	}
}
